package com.example.homework.login;

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.homework.R;
import com.example.homework.baseActivity.MainActivity;
import com.example.homework.db.UserDbHelper;
import android.database.Cursor;

public class LoginActivity extends AppCompatActivity {
    private EditText userEditText;
    private EditText pwoEditText;
    private Button buttonLogin;
    private Button buttonRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 通过findViewById方法找到布局文件中的对应组件
        userEditText = findViewById(R.id.user);
        pwoEditText = findViewById(R.id.pwo);
        buttonLogin = findViewById(R.id.button5);
        buttonRegister = findViewById(R.id.buttonR);

        // 设置登录按钮的点击事件监听器
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = userEditText.getText().toString().trim();
                String password = pwoEditText.getText().toString().trim();

                if (validateLogin(username, password)) {
                    // 登录成功，跳转到MainActivity
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 设置注册按钮的点击事件监听器，跳转到注册界面
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    // 从数据库验证用户名和密码是否匹配的方法
    private boolean validateLogin(String username, String password) {
        UserDbHelper dbHelper = new UserDbHelper(this);
        Cursor cursor = dbHelper.getUserByUsername(username);
        boolean result = false;
        if (cursor.moveToFirst()) {
            int passwordColumnIndex = cursor.getColumnIndex(UserDbHelper.COLUMN_PASSWORD);
            if (passwordColumnIndex >= 0) {
                String storedPassword = cursor.getString(passwordColumnIndex);
                result = password.equals(storedPassword);
            } else {
                // 列索引为 -1，说明列不存在，这里可以根据实际情况进行更合适的错误处理，比如记录日志、提示用户等
                Log.e("LoginActivity", "数据库中不存在密码列，可能出现异常");
            }
        }
        cursor.close();
        return result;
    }
}